import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:kq_flutter_core_widget/config/kq_core_global.dart';
import 'package:kq_flutter_pad_widgets/widgets/dialog/kq_pad_list_choose_dialog.dart';

import '../../resources/l10n/kq_pad_intl.dart';
import 'kq_confirm_dialog.dart';
import 'kq_custom_dialog.dart';
import 'kq_input_dialog.dart';
import 'kq_list_dialog.dart';
import 'kq_msg_dialog.dart';
import 'kq_opt_dialog.dart';

enum DialogBtnType { normal, radius }

/// 通用对话框，简化调用过程
class KqPadDialog {
  ///消息对话框
  ///
  /// 顶部标题
  /// 中间内容
  /// 底部1个按钮-我知道了
  static showMsgDialog(
      {String? title,
      required String msg,
      String? btnText,
      double? lineHeight,
      bool barrierDismissible = true,
      GestureTapCallback? onBtnTap,
      Function()? onDismiss}) {
    showDialog(
        context: KqCoreGlobal.globalContext,
        barrierDismissible: barrierDismissible,
        barrierColor: Colors.black.withOpacity(0.2),
        builder: (context) {
          return KqPadMsgDialog(
            titleString: title,
            msg: msg,
            lineHeight: lineHeight,
            btnText: btnText ?? KqPadIntl.currentResource.known,
            onBtnTap: () {
              Navigator.pop(context);
              onBtnTap?.call();
            },
          );
        }).then((value) => onDismiss?.call());
  }

  /// 操作对话框，
  ///
  /// 顶部标题和关闭按钮
  /// 中间自定义内容
  /// 底部1个按钮-确定
  static showOptDialog(
      {String? title,
      required Widget child,
      String? btnText,
      double? width,
      double? height,
      bool barrierDismissible = true,
      GestureTapCallback? onBtnTap,
      Function()? onDismiss}) {
    showDialog(
        context: KqCoreGlobal.globalContext,
        barrierDismissible: barrierDismissible,
        barrierColor: Colors.black.withOpacity(0.2),
        builder: (context) {
          return KqPadOptDialog(
            titleString: title,
            btnText: btnText,
            width: width,
            height: height,
            child: child,
            onBtnTap: () {
              Navigator.pop(context);
              onBtnTap?.call();
            },
          );
        }).then((value) => onDismiss?.call());
  }

  /// 确认对话框，
  ///
  /// 顶部标题
  /// 中间内容
  /// 底部两个按钮-取消和确定
  static showConfirmDialog(
      {String? title,
      required String msg,
      String? leftBtnText,
      String? rightBtnText,
      bool barrierDismissible = true,
      GestureTapCallback? onCancel,
      GestureTapCallback? onConfirm,
      Function()? onDismiss}) {
    showDialog(
        context: KqCoreGlobal.globalContext,
        barrierDismissible: barrierDismissible,
        barrierColor: Colors.black.withOpacity(0.2),
        builder: (context) {
          return KqPadConfirmDialog(
            titleString: title,
            msg: msg,
            leftBtnText: leftBtnText,
            rightBtnText: rightBtnText,
            onLeftBtnTap: () {
              Navigator.pop(context);
              onCancel?.call();
            },
            onRightBtnTap: () {
              Navigator.pop(context);
              onConfirm?.call();
            },
          );
        }).then((value) => onDismiss?.call());
  }

  /// 输入对话框
  ///
  /// defValue : 默认值
  /// maxLines : 最大行数，默认1
  /// multiline : 是否支持多行，默认false
  /// allowEmpty : 内容为空是否允许确定，默认true
  /// inputTextAlign : 输入框内容对齐方式
  /// inputFormatters : 输入框内容格式限制
  /// inputType : 键盘类型
  /// autoDismissWhenTapMiddle : 是否点击中间按钮自动关闭对话框，默认true
  /// onEmptyCallback : allowEmpty = false 时，输入为空提交回调
  /// onConfirm : 确认点击回调
  static showInputDialog(String title,
      {String? placeHolder,
      String? defValue,
      bool multiline = false,
      bool allowEmpty = true,
      bool barrierDismissible = true,
      TextAlign? inputTextAlign,
      TextInputType? inputType,
      String? leftBtnText,
      String? rightBtnText,
      String? middleBtnText,
      int? maxCharCount,
      List<TextInputFormatter>? inputFormatters,
      bool autoDismissWhenTapLeft = true,
      bool autoDismissWhenTapRight = true,
      bool autoDismissWhenTapMiddle = true,
      bool showShadow = true,
      double Function(double bottomPadding)? bottomPaddingBuilder,
      Function()? onEmptyCallback, //allowEmpty = false 时，输入为空提交回调
      Function(String value)? onLeftBtnClick,
      Function(String value)? onMiddleBtnClick,
      required Function(String value) onConfirm,
      Function()? onDismiss}) {
    showDialog(
        context: KqCoreGlobal.globalContext,
        barrierDismissible: barrierDismissible,
        barrierColor: Colors.black.withOpacity(0.2),
        builder: (context) {
          return KqPadInputDialog(
            defValue: defValue,
            titleString: title,
            enableClearButton: true,
            multiline: multiline,
            placeHolder: placeHolder,
            inputType: inputType ??
                (multiline ? TextInputType.multiline : TextInputType.text),
            inputTextAlign: inputTextAlign,
            inputFormatters: inputFormatters,
            bottomPaddingBuilder: bottomPaddingBuilder,
            maxLines: 4,
            maxCharCount: maxCharCount,
            editController: TextEditingController(),
            leftBtnText: leftBtnText,
            rightBtnText: rightBtnText,
            middleBtnText: middleBtnText,
            showShadow: showShadow,
            onLeftBtnTap: (value) {
              if (onLeftBtnClick == null) {
                Navigator.pop(context);
              } else {
                if (autoDismissWhenTapLeft) {
                  Navigator.pop(context);
                }
                onLeftBtnClick.call(value);
              }
            },
            onMiddleBtnTap: (value) {
              if (autoDismissWhenTapMiddle) {
                Navigator.pop(context);
              }
              onMiddleBtnClick?.call(value);
            },
            onRightBtnTap: (value) {
              if (allowEmpty || value.isNotEmpty) {
                if (autoDismissWhenTapRight) {
                  Navigator.pop(context);
                }
                onConfirm(value);
              } else {
                if (onEmptyCallback != null) {
                  onEmptyCallback();
                }
              }
            },
          );
        }).then((value) => onDismiss?.call());
  }

  /// 显示loading
  static void showLoading({String? msg, bool showMask = false}) {
    EasyLoading.show(
        status: msg ?? KqPadIntl.currentResource.loading,
        maskType:
            showMask ? EasyLoadingMaskType.black : EasyLoadingMaskType.clear);
  }

  /// 关闭loading
  static void closeLoading() {
    EasyLoading.dismiss();
  }

  // 自定义弹窗
  static showCustomDialog(
      {String? title,
      required Widget customWidget,
      Widget? Function(BuildContext context, Function()? onCancel)?
          customBtnWidget,
      String? leftBtnText,
      String? rightBtnText,
      Color? leftBtnColor,
      Color? rightBtnColor,
      Color? leftBtnBgColor,
      Color? rightBtnBgColor,
      bool barrierDismissible = true,
      Function()? onLeftTap,
      Function()? onRightTap,
      bool isShowLeft = true,
      bool isShowRight = true,
      double? customTopPadding,
      double? customBottomPadding,
      double? dialogWidth,
      double? radius,
      double Function(double bottomPadding)? bottomPaddingBuilder,
      Function()? onDismiss,
      Function(BuildContext context)? onRightTapDismissDialog, //外部控制弹窗消失
      bool isShowClose = false,
      DialogBtnType btnType = DialogBtnType.normal}) {
    showDialog(
        context: KqCoreGlobal.globalContext,
        barrierDismissible: barrierDismissible,
        builder: (context) {
          return KqPadCustomDialog(
            titleString: title,
            customWidget: customWidget,
            customBtnWidget: customBtnWidget?.call(context, onLeftTap),
            bottomPaddingBuilder: bottomPaddingBuilder,
            leftBtnText: leftBtnText,
            //左侧灰色
            rightBtnText: rightBtnText,
            //右侧蓝色
            leftBtnColor: leftBtnColor,
            rightBtnColor: rightBtnColor,
            leftBtnBgColor: leftBtnBgColor,
            rightBtnBgColor: rightBtnBgColor,
            isShowLeft: isShowLeft,
            isShowRight: isShowRight,
            customTopPadding: customTopPadding,
            customBottomPadding: customBottomPadding,
            dialogWidth: dialogWidth,
            radius: radius,
            isShowClose: isShowClose,
            btnType: btnType,
            onLeftBtnTap: () {
              Navigator.pop(context);
              onLeftTap?.call();
            },
            onRightBtnTap: () {
              if (onRightTapDismissDialog == null) {
                Navigator.pop(context);
              } else {
                onRightTapDismissDialog.call(context);
              }
              onRightTap?.call();
            },
          );
        }).then((value) => onDismiss?.call());
  }

  /// 列表对话框
  static showListDialog<T>(List<T> items,
      {bool barrierDismissible = true,
      String Function(int index, T item)? nameConvert,
      Function(int index, T item)? callback,
      bool searchEnable = false,
      bool Function(String searchText, T item)? onSearchItem,
      Function()? onDismiss}) {
    if (items.isEmpty) {
      return;
    }
    showDialog(
        context: KqCoreGlobal.globalContext,
        barrierDismissible: barrierDismissible,
        barrierColor: Colors.black.withOpacity(0.2),
        builder: (context) {
          return KqPadListDialog(
              items: items,
              nameConvert: nameConvert,
              searchEnable: searchEnable,
              onSearchItem: onSearchItem,
              callback: (index, item) {
                Navigator.pop(context);
                if (callback != null) {
                  callback(index, item);
                }
              });
        }).then((value) => onDismiss?.call());
  }

  /// 列表选择弹窗
  static void showPadListChooseDialog<T>(
      {bool barrierDismissible = true,
      String? title,
      required List<T> Function() itemList,
      String Function(int index, T item)? itemContent,
      Widget Function(int index, T item)? itemBuilder,
      required bool Function(int index, T item) isSelected,
      required void Function(int index, T item) selectedItem,
      List<T> Function(String content)? onSearch,
      List<T> Function(String content)? onSubmit}) {
    showDialog(
      context: KqCoreGlobal.globalContext,
      barrierDismissible: barrierDismissible,
      barrierColor: Colors.black.withOpacity(0.2),
      builder: (context) {
        if (itemBuilder != null) {
          if (onSearch != null || onSubmit != null) {
            return KqPadListChooseDialog(
                title: title ?? '',
                itemBuilder: (index, item) {
                  return itemBuilder.call(index, item);
                },
                itemList: () {
                  return itemList();
                },
                selectedItem: (index, item) => selectedItem(index, item),
                onSearch: (content) => onSearch!(content),
                onSubmit: (content) => onSearch!(content),
                isSelected: (index, item) {
                  print(item);
                  return isSelected(index, item);
                });
          }
          return KqPadListChooseDialog(
              title: title ?? '',
              itemBuilder: (index, item) {
                return itemBuilder.call(index, item);
              },
              itemList: () {
                return itemList();
              },
              selectedItem: (index, item) => selectedItem(index, item),
              isSelected: (index, item) => isSelected(index, item));
        } else {
          if (onSearch != null || onSubmit != null) {
            return KqPadListChooseDialog(
                title: title ?? '',
                itemContent: (index, item) {
                  return itemContent!(index, item);
                },
                itemList: () {
                  return itemList();
                },
                selectedItem: (index, item) => selectedItem(index, item),
                onSearch: (content) => onSearch!(content),
                onSubmit: (content) => onSearch!(content),
                isSelected: (index, item) => isSelected(index, item));
          }
          return KqPadListChooseDialog(
              title: title ?? '',
              itemContent: (index, item) {
                return itemContent!(index, item);
              },
              itemList: () {
                return itemList();
              },
              selectedItem: (index, item) => selectedItem(index, item),
              isSelected: (index, item) => isSelected(index, item));
        }
      },
    );
  }
}
